/* =======================================================================
 * jQuery.Huitextarealength.js v2.1 字数限制
 * http://www.h-ui.net/
 * Created & Modified by guojunhui
 * Date modified 2024.09.12
 * Copyright 2017-2024 郭俊辉 All rights reserved.
 * Licensed under MIT license.
 * http://opensource.org/licenses/MIT
 * 使用方法：
  $(".hui-textarea").Huitextarealength({
    minlength:10,
    maxlength:200.
  });
 * ========================================================================*/
!function($) {
  $.fn.Huitextarealength = function(options) {
    var defaults = {
      minlength: 0,
      maxlength: 300,
      errorClass: "error",
      exceed: true
    };
    var settings = $.extend({}, defaults, options);

    this.each(function() {
      var that = $(this);
      var v = that.val();
      var l = v.length;
      var str = '<p class="hui-textarea-numberbar"><em class="hui-textarea-length">' + l + '</em>/' + settings.maxlength + '</p>';
      that.parent().append(str);

      that.on("keyup input", function() {
        v = $.trim(that.val());
        l = v.length;

        if (l > settings.maxlength) {
          if (settings.exceed) {
            that.addClass(settings.errorClass);
          } else {
            v = v.substring(0, settings.maxlength);
            that.val(v);
          }
        } else if (l < settings.minlength) {
          that.addClass(settings.errorClass);
        } else {
          that.removeClass(settings.errorClass);
        }
        that.parent().find(".hui-textarea-length").text(l);
      });

      that.on("blur", function() {
        v = $.trim(that.val());
        l = v.length;
        if (l > settings.maxlength && !settings.exceed) {
          that.addClass(settings.errorClass);
        } else if (l < settings.minlength) {
          that.addClass(settings.errorClass);
        } else {
          that.removeClass(settings.errorClass);
        }
      });
    });
  };
}(window.jQuery);